package com.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {

    // 交换机名称
    public static final String CHAT_EXCHANGE = "chat_exchange";
    public static final String DLX_EXCHANGE = "dlx_exchange";
    
    // 队列名称前缀
    public static final String USER_QUEUE_PREFIX = "user.queue.";
    public static final String DLX_QUEUE_PREFIX = "dlx.queue.";
    
    // 路由键
    public static final String MESSAGE_ROUTING_KEY = "user.message";
    public static final String DLX_ROUTING_KEY = "dlx.message";

    @Value("${spring.rabbitmq.host}")
    private String host;

    /**
     * 消息转换器
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * RabbitTemplate配置
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(messageConverter());
        return template;
    }

    /**
     * 监听器容器工厂
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(messageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

    /**
     * 聊天消息交换机
     */
    @Bean
    public DirectExchange chatExchange() {
        return new DirectExchange(CHAT_EXCHANGE, true, false);
    }

    /**
     * 死信交换机
     */
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(DLX_EXCHANGE, true, false);
    }

    /**
     * 用户队列（动态创建）
     * 注意：实际使用时需要根据用户ID动态创建队列
     */
    @Bean
    public Queue userQueue() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DLX_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", DLX_ROUTING_KEY);
        arguments.put("x-message-ttl", 60000); // 60秒过期
        arguments.put("x-max-length", 1000); // 最大队列长度
        
        return new Queue(USER_QUEUE_PREFIX + "default", true, false, false, arguments);
    }

    /**
     * 死信队列
     */
    @Bean
    public Queue dlxQueue() {
        return new Queue(DLX_QUEUE_PREFIX + "default", true);
    }

    /**
     * 绑定用户队列到聊天交换机
     */
    @Bean
    public Binding userQueueBinding() {
        return BindingBuilder.bind(userQueue()).to(chatExchange()).with(MESSAGE_ROUTING_KEY);
    }

    /**
     * 绑定死信队列到死信交换机
     */
    @Bean
    public Binding dlxQueueBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(DLX_ROUTING_KEY);
    }

    /**
     * 创建用户专属队列的工厂方法
     * 在实际使用中，需要根据用户ID动态创建队列
     */
    public Queue createUserQueue(String userId) {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", DLX_EXCHANGE);
        arguments.put("x-dead-letter-routing-key", DLX_ROUTING_KEY);
        arguments.put("x-message-ttl", 60000);
        arguments.put("x-max-length", 1000);
        
        return new Queue(USER_QUEUE_PREFIX + userId, true, false, false, arguments);
    }

    /**
     * 创建死信队列的工厂方法
     */
    public Queue createDlxQueue(String userId) {
        return new Queue(DLX_QUEUE_PREFIX + userId, true);
    }
}
